package com.banshuibao.bsb_android.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.ClassListAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.MediaModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshListView;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.IntentManager;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zyh on 2017/12/21.
 */

public class ClassListFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private ClassListAdapter adapter;

    private int sinceId = 1;

    private MediaModel.Data data;

    private LinearLayout.LayoutParams params;

    private Dialog buyDialog;

    public ClassListFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_class_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pullToRefreshListView = view.findViewById(R.id.pull);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.setDivider(null);
        Drawable drawable = getResources().getDrawable(R.drawable.noloading);
        ImageView imageView = new ImageView(getActivity());
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        imageView.setLayoutParams(params);
        imageView.setImageDrawable(drawable);
        listView.setEmptyView(imageView);
        adapter = new ClassListAdapter(getActivity());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (adapter != null) {
                    MediaModel.Data data = adapter.getItem(i - 1);
                    ClassListFragment.this.data = data;
                    buyMedia(data);
                }
            }
        });
        loadNewData();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        loadNewData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        loadMedia(sinceId, sinceId + 10);
    }

    private void loadNewData() {
        if (adapter != null) {
            int end = adapter.getCount() > 10 ? adapter.getCount() : 10;
            sinceId = 1;
            loadMedia(sinceId, end);
        }
    }

    private void loadMedia(final int s, final int e) {
        MediaModel.Body body = new MediaModel.Body();
        body.setSinceId(s);
        body.setMaxId(e);
        body.setType("all");
        body.setVideoType("2");
        HttpUtil.doPost(Constants.Url.VIDEO_LIST, body, new HttpResponse(getActivity(), MediaModel.class) {
            @Override
            public void onResult(Object obj) {
                MediaModel mediaModel = (MediaModel) obj;
                sinceId += mediaModel.getRows();
                if (adapter != null) {
                    if (s == 1) {
                        adapter.setData(mediaModel.getData());
                    } else
                        adapter.addData(mediaModel.getData());
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                pullComplete();
            }
        });
    }

    void buyMedia(final MediaModel.Data data) {
        MediaModel.BuyBody buyBody = new MediaModel.BuyBody();
        buyBody.setUuid(data.getId());
        HttpUtil.doPost(Constants.Url.IS_BUY, buyBody, new HttpResponse(getActivity()) {
            @Override
            public void onResult(Object obj) {
                JSONObject jsonObject = null;
                JSONObject jsonObject1 = null;
                try {
                    jsonObject = new JSONObject((String) obj);
                    jsonObject1 = jsonObject.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject1 != null) {
                    String type = jsonObject1.optString("type");
                    String vid = jsonObject1.optString("vid");
                    if ("0".equals(type) && !TextUtils.isEmpty(vid)) {
                        IntentManager.goMediaPlayActivity(getActivity(), vid, Constants.Url.VIDEO, data.getId(), data.getImage());
                    } else {
                        buyDialog = DialogUtils.payDialog(getActivity(), "您可以支付" + String.valueOf(data.getPrice()) + "元购买单集或支付365元购买会员卡观看所有视频!",
                                data.getId(), String.valueOf(data.getPrice()), data.getTitle(), 4);
                        if (!buyDialog.isShowing())
                            buyDialog.show();
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200)
                buyMedia(ClassListFragment.this.data);
        }
    }

    private void pullComplete() {
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.clear();
            adapter = null;
        }
    }
}
